package com.cskaoyan.service;

import com.cskaoyan.bean.Keyword;
import com.cskaoyan.bean.KeywordExample;
import com.cskaoyan.bean.SearchHistory;
import com.cskaoyan.bean.SearchHistoryExample;
import com.cskaoyan.mapper.KeywordMapper;
import com.cskaoyan.mapper.SearchHistoryMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    KeywordMapper keywordMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Override
    public Map<String, Object> indexSearch() {
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        keywordExample.setOrderByClause("is_default desc");
        criteria.andIsHotEqualTo(true);
        criteria.andDeletedEqualTo(false);
        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);
        Keyword defaultKeyword = keywords.get(0);
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        HashMap<String,Object> map = new HashMap<>();
        map.put("defaultKeyword",defaultKeyword);
        map.put("hotKeywordList",keywords);
        map.put("historyKeywordList",searchHistories);
        return map;
    }

    @Override
    public List<String> searchHelper(String keywordpre) {
        String keyword = "%"+keywordpre+"%";
        List<String> keywords = keywordMapper.selectKeyword(keyword);
        SearchHistory searchHistory = new SearchHistory();
        Subject subject = SecurityUtils.getSubject();
        Integer userId = (Integer) subject.getPrincipal();
        searchHistory.setUserId(userId);
        searchHistory.setFrom("wx");
        searchHistory.setDeleted(false);
        Date date = new Date();
        searchHistory.setAddTime(date);
        searchHistory.setUpdateTime(date);
        searchHistory.setKeyword(keywordpre);
        searchHistoryMapper.insert(searchHistory);
        return keywords;
    }

    @Override
    public void clearHistory() {
        Integer deleted = 1;
        keywordMapper.updateAllDeleted(deleted);
    }
}
